﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Traceability.Common.Domain;
using Traceability.Common.Dtos;
using Traceability.Common.Infrastructure.InterFaces;
using Traceability.Enum;

namespace Traceability.Bais.API.Appliction.Command.Users
{
    public class PremissionListHandler : IRequestHandler<PermissionListCommon, Result<List<PremissionDto>>>
    {
        private readonly IBaseRepository<Permission> permissionRep;
        private readonly IMapper mapper;
        public PremissionListHandler(IBaseRepository<Permission> _permissionRep,IMapper mapper)
        {
            this.permissionRep = _permissionRep;
            this.mapper = mapper;
        }
        /// <summary>
        /// 测试数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result<List<PremissionDto>>> Handle(PermissionListCommon request, CancellationToken cancellationToken)
        {
            var result = new Result<List<PremissionDto>>() { Code=(int)CommonErrorCode.search};
            try
            {
                var permissions = await (await permissionRep.GetAll()).Where(c=>c.IsDelete==false).ToListAsync();
                if(!string.IsNullOrEmpty(request.PermissionName))
                {
                    permissions = permissions.Where(c => c.PermissionName == request.PermissionName).ToList();
                }

                var n = mapper.Map<List<PremissionDto>>(permissions);
                // 此处模拟数据
                if (permissions != null&& permissions.Any())
                {
                
                    result.list = n;
                } 

            }
            catch (Exception)
            {
                result.Msg = "查询失败";
                throw;
            }
            return result;
        }
    }
}
//result.Data = permissions.Select((c,index)=>new PremissionDto
//{
//    PermissionId = c.PermissionId,
//    PermissionName = c.PermissionName,
//    URL = c.URL,
//    PerantId  = index + 1                     
//}).ToList();